Vue.directive('focus',{
  inserted(el){
    el.focus()
  }, 
})
let app=new Vue({
  el: '#todoApp',
  data:{
    todos: [],
    inputValue:'',
    filterStatus:'all'
  },
  computed:{
    leftCount(){
      return this.todos.filter(todo=>!todo.completed).length
    },
    filterTodos(){
      switch(this.filterStatus){
        case 'active':
          return this.todos.filter(todo=>!todo.completed)
        case 'completed':
          return this.todos.filter(todo=>todo.completed)
        default:
          return this.todos
      }
    },
    checkAllStatus(){
      let arr=this.todos.filter(todo=>todo.completed===true)
      return arr.length===this.todos.length?true:false
    },
  },
  methods: {
    addTodo(){
      if(!this.inputValue){
        return
      }
      this.todos.push({
        id:this.todos.length===0?1:this.todos[this.todos.length-1].id+1,
        content:this.inputValue,
        completed: false,
        isEditing: false
      })
      this.inputValue=''
    },
    toggleAll(event){
      this.todos.forEach(todo=>todo.completed=event.target.checked)
    },
    removeTodo(id){
      this.todos=this.todos.filter(todo=>todo.id!==id)
    },
    editTodo(id){
      this.todos.forEach(todo=>{
        if(todo.id===id){
          todo.isEditing=true
        }
      })
    },
    exitEdit(id){
      for(let i=0;i<this.todos.length;i++){
        if(this.todos[i].id===id){
          if(!this.todos[i].content.trim().length){
            return this.todos.splice(i,1)
          }
          this.todos[i].isEditing=false
        }
      }
    },
    removeAllCompleted(){
      this.todos=this.todos.filter(todo=>!todo.completed)
    },
  },
  directives:{
    editingFocus:{
      update(el,binding){
          if(binding.value){
              el.focus();
          }
      },
    }
  }
})
window.onhashchange=()=>{
  let hash=window.location.hash.substr(2)||'all'
  app.filterStatus=hash
}
window.onhashchange()
